package cn.acewill.yxd.yunxundian.ui.sign;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.YXDAPP;
import cn.acewill.yxd.yunxundian.adapter.SignStoreAdapter;
import cn.acewill.yxd.yunxundian.model.CommonMapBean;
import cn.acewill.yxd.yunxundian.model.Shop;
import cn.acewill.yxd.yunxundian.pubClass.pubClass;
import cn.acewill.yxd.yunxundian.ui.MainActivity;
import cn.acewill.yxd.yunxundian.utils.baiduUtils.BaiduMapUtils;
/**
 * Created by AAA on 2017/4/6.
 */

public class SignMainActivity extends BaseActivity implements AdapterView.OnItemClickListener,BaiduMap.OnMarkerClickListener{
    protected YXDAPP yxdapp=new YXDAPP();
    protected DbManager db = x.getDb(yxdapp.getDaoConfig());
    private MapView myMap;
    private BaiduMap mBaiduMap;
    boolean isFirstLoc=true;
    private boolean isMyfirst=true;
    private ListView storelist;
    private TextView searchFor;
    public static LatLng MyPosition;
    private Handler handler=new Handler();
    private List<Shop> shopList;
    private ArrayList<Shop> searchList;
    public Context mContext;
    public LocationClient mLocationClient = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTitleBar("签到");
        setContentView(R.layout.sign_main);
        super.onCreate(savedInstanceState);
        initView();
        mBaiduMap=myMap.getMap();
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setOnMarkerClickListener(this);

        PackageManager pm = getPackageManager();
        boolean permission = (PackageManager.PERMISSION_GRANTED ==
                pm.checkPermission("android.permission.ACCESS_FINE_LOCATION", "cn.acewill.yxd.yunxundian"));
        boolean permission1 = (PackageManager.PERMISSION_GRANTED ==
                pm.checkPermission("android.permission.ACCESS_COARSE_LOCATION", "cn.acewill.yxd.yunxundian"));
        if(!permission || !permission1)
        {
            showAnimaDialog(SignMainActivity.this,"请开启系统定位服务");
            finish();
        }
        mLocationClient = new LocationClient(getApplicationContext());
        initLocation();
        //声明LocationClient类
        mLocationClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                MyLocationData myLocationData = new MyLocationData.Builder()
                        .accuracy(bdLocation.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(100).latitude(bdLocation.getLatitude())
                        .longitude(bdLocation.getLongitude()).build();

                mBaiduMap.setMyLocationData(myLocationData);
                MyPosition = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                if(isMyfirst)
                {
                    MapStatusUpdate mapStatus = MapStatusUpdateFactory.newLatLngZoom(new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude()), 18);
                    mBaiduMap.setMapStatus(mapStatus);
                    isMyfirst=false;
                }
            }

            @Override
            public void onConnectHotSpotMessage(String s, int i) {

            }
        });
        mLocationClient.start();

        mContext=this;
        OnLocation();
    }

    private void initLocation(){
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备

        option.setCoorType("bd09ll");
        //可选，默认gcj02，设置返回的定位结果坐标系

        int span=30000;
        option.setScanSpan(span);
        //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的

        option.setIsNeedAddress(false);
        //可选，设置是否需要地址信息，默认不需要

        option.setOpenGps(true);
        //可选，默认false,设置是否使用gps

        option.setLocationNotify(true);
        //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果

        option.setIsNeedLocationDescribe(false);
        //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”

        option.setIsNeedLocationPoiList(false);
        //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到

        option.setIgnoreKillProcess(true);
        //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死

        option.SetIgnoreCacheException(false);
        //可选，默认false，设置是否收集CRASH信息，默认收集

        option.setEnableSimulateGps(false);
        //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要

        mLocationClient.setLocOption(option);
    }
    public void initView() {
        int userId = MainActivity.id;
        this.myMap = (MapView) findViewById(R.id.myMap);
        this.storelist= (ListView) findViewById(R.id.storelist);
        storelist.setOnItemClickListener(this);
        this.searchFor= (TextView) findViewById(R.id.searchFor);



        try {
            List<CommonMapBean> cmbList=db.selector(CommonMapBean.class)
                    .where("cmType","=","role")
                    .and("ServerId","=", userId)
                    .findAll();
            int isall=1;
            if(cmbList!=null)
            {
                for(CommonMapBean cc:cmbList)
                {
                    if(cc.getCmValue().equals("OM"))
                        isall=1;
                    else if(cc.getCmValue().equals("OC"))
                        isall=1;
                    else
                        isall=1;
                }
            }
            if(isall==0)
            shopList = db.selector(Shop.class).where("ocid", "=", userId).or("omid","=", userId).findAll();
            else
                shopList=db.selector(Shop.class).findAll();
        } catch (DbException e) {
            e.printStackTrace();
        }
        searchFor.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                //文本改变前
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                //文本改变后
             handler.post(eChange);
            }
        });
        searchFor.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {//EditorInfo.IME_ACTION_SEARCH、EditorInfo.IME_ACTION_SEND等分别对应EditText的imeOptions属性
                    //TODO回车键按下时要执行的操作
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                }
                return false;
            }
        });
    }
    public void OnLocation(){

        BaiduMapUtils.getInstance(this).getLocate(new BaiduMapUtils.OnLocationMapListener() {
            @Override
            public void getCurrLocation(BDLocation location) throws DbException {
                MyLocationData locData = new MyLocationData.Builder()
                        .accuracy(location.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(100).latitude(location.getLatitude())
                        .longitude(location.getLongitude()).build();

                MyPosition=new LatLng(location.getLatitude(),location.getLongitude());
                if((int)location.getAltitude()==0)
                {
                        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                            if (ActivityCompat.checkSelfPermission(SignMainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(SignMainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                // TODO: Consider calling
                                //    ActivityCompat#requestPermissions
                                // here to request the missing permissions, and then overriding
                                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                //                                          int[] grantResults)
                                // to handle the case where the user grants the permission. See the documentation
                                // for ActivityCompat#requestPermissions for more details.
                                return;
                            }
                            Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location1 != null) {
                                double[] latlng = (pubClass.wgs2bd(location1.getLatitude(), location1.getLongitude()));
                                MyPosition = new LatLng(latlng[0], latlng[1]);
                                locData = new MyLocationData.Builder()
                                        .accuracy(location.getRadius())
                                        // 此处设置开发者获取到的方向信息，顺时针0-360
                                        .direction(100).latitude(latlng[0])
                                        .longitude(latlng[1]).build();
                            }

                        }
                }
                mBaiduMap.setMyLocationData(locData);
                if (isFirstLoc) {
                    isFirstLoc = false;
                    LatLng ll = new LatLng(location.getLatitude(),
                            location.getLongitude());
                    if((int)location.getAltitude()==0)
                    {
                            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                                if (ActivityCompat.checkSelfPermission(SignMainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(SignMainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                                    // TODO: Consider calling
                                    //    ActivityCompat#requestPermissions
                                    // here to request the missing permissions, and then overriding
                                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                    //                                          int[] grantResults)
                                    // to handle the case where the user grants the permission. See the documentation
                                    // for ActivityCompat#requestPermissions for more details.
                                    return;
                                }
                                Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                if (location1 != null) {
                                    double[] latlng = (pubClass.wgs2bd(location1.getLatitude(), location1.getLongitude()));
                                    ll = new LatLng(latlng[0], latlng[1]);
                                }

                            }
                    }
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(ll).zoom(18.0f);
                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                }
                handler.post(SortDistance);
                handler.post(markMap);
            }
        });
    }

    //检索
    Runnable eChange = new Runnable() {
        @Override
        public void run() {
            String Data = searchFor.getText().toString().trim();
            getDataSub(Data);
            SignStoreAdapter adapter = new SignStoreAdapter(SignMainActivity.this, searchList, new SignStoreAdapter.goSignClick() {
                @Override
                public void goToSign(Shop bean) {
                    //showToast("我要签到");
                    Intent in = new Intent(SignMainActivity.this, SignInActivity.class);
                    in.putExtra("ycol", bean.getyCol());
                    in.putExtra("xcol", bean.getxCol());
                    in.putExtra("shopId", bean.getID());
                    in.putExtra("shopName", bean.getShopName());
                    in.putExtra("checktype", "in");
                    startActivity(in);
                }
            });
            adapter.notifyDataSetChanged();
            storelist.setAdapter(adapter);
        }
    };
    public void getDataSub(String Data){
        if(shopList==null)
            return;
        int length=shopList.size();
        searchList=new ArrayList<>();
        for (int i=0;i<length;i++){
            if(shopList.get(i).getShopName()!=null && shopList.get(i).getShopNum()!=null&&
                    (shopList.get(i).getShopName().contains(Data)|| shopList.get(i).getShopNum().contains(Data))){
                searchList.add(shopList.get(i));
            }
        }
    }

    //加载数据并排序
    Runnable SortDistance=new Runnable() {
        @Override
        public void run() {
            if(shopList!=null) {
                Collections.sort(shopList, new SortBuyDistance());
                SignStoreAdapter adapter = new SignStoreAdapter(SignMainActivity.this, shopList, new SignStoreAdapter.goSignClick() {
                    @Override
                    public void goToSign(Shop bean) {
                        Intent in = new Intent(SignMainActivity.this, SignInActivity.class);
                        in.putExtra("ycol", bean.getyCol());
                        in.putExtra("xcol", bean.getxCol());
                        in.putExtra("shopId", bean.getID());
                        in.putExtra("shopName", bean.getShopName());
                        startActivity(in);
                    }
                });
                storelist.setAdapter(adapter);
            }
            else{
                showAnimaDialog(mContext,"您尚未分配门店，或系统尚未同步完成，请重新登录");
                finish();
            }
        }
    };

    @Override
    public boolean onMarkerClick(Marker marker) {
        LatLng position=marker.getPosition();
        goMapMark(position);
        View view=LayoutInflater.from(this).inflate(R.layout.showtext, (ViewGroup) getWindow().getDecorView(),false);
        TextView shopName= (TextView) view.findViewById(R.id.shopName);
        InfoWindow window=new InfoWindow(view,position,1);
        shopName.setText(marker.getTitle());
        mBaiduMap.showInfoWindow(window);
        searchFor.setText(marker.getTitle());
        return true;
    }

    class SortBuyDistance implements Comparator {

        @Override
        public int compare(Object o1, Object o2) {
            Shop shop1 = (Shop) o1;
            Shop shop2 = (Shop) o2;
            double ycol1 = shop1.getyCol();
            double xcol1 = shop1.getxCol();
            LatLng ll = new LatLng(ycol1, xcol1);
            int  dist1 = (int)DistanceUtil.getDistance(ll, MyPosition);
            double ycol2 = shop2.getyCol();
            double xcol2 = shop2.getxCol();
            LatLng l2 = new LatLng(ycol2, xcol2);
            int dist2 = (int)DistanceUtil.getDistance(l2, MyPosition);
            //正则表达式转化字符
            String regEx = "[^0-9]";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(dist1 + "");
            String d1 = m.replaceAll("").trim();
            Matcher n = p.matcher(dist2 + "");
            String d2 = n.replaceAll("").trim();
            if (Integer.parseInt(d1) > Integer.parseInt(d2)) {
                return 1;
            } else if (Integer.parseInt(d1) == Integer.parseInt(d2)) {
                return 0;
            } else {
                return -1;
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Shop shop= (Shop) parent.getItemAtPosition(position);
        LatLng ll=new LatLng(shop.getyCol(),shop.getxCol());
        goMapMark(ll);
    }

    Runnable markMap=new Runnable() {
        @Override
        public void run() {
            if(shopList!=null) {
                for (int i = 0; i < shopList.size(); i++) {
                    LatLng point = new LatLng(shopList.get(i).getyCol(), shopList.get(i).getxCol());
                    String shopName = shopList.get(i).getShopName();
                    BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.mipmap.icon_gcoding);
                    OverlayOptions options = new MarkerOptions().position(point).icon(bitmapDescriptor).title(shopName);
                    mBaiduMap.addOverlay(options);
                }
            }
        }
    };
    //地图的联动
    private void goMapMark(LatLng ll){
        MapStatus mapStatus =new MapStatus.Builder().target(ll).zoom(18).build();
        MapStatusUpdate mapStatusUpdate=MapStatusUpdateFactory.newMapStatus(mapStatus);
        mBaiduMap.setMapStatus(mapStatusUpdate);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        setResult(100);
    }
}
